import {buildSimpleApp, initRootEvents} from "./webcom.js";

function isSupportPopover() {
    return CSS.supports('selector(:popover-open)')
}
import {BaseEle} from "./core.js";

class DialogPopover extends BaseEle {
    constructor() {
        super();
        this.dialogFrameWorkOption = {}
        this.attachShadow({ mode: 'open' });
        this._shadowRoot = this.shadowRoot;
        this._shadowRoot.innerHTML = `
          <style>
            :host { display: inline-block; }
            
            /*:host(.dialog-open)::after {*/
            /*    content: '';*/
            /*    display: block;*/
            /*    position: fixed;*/
            /*    left: 0;*/
            /*    top: 0;*/
            /*    width: 100%;*/
            /*    height: 100%;*/
            /*    background-color: rgba(0, 0, 0, .5);*/
            /*    pointer-events: none;*/
            /*    z-index: 1;*/
            /*}*/
            
            #dialog {
              padding: 1rem;
              border: var(--z-def-border);
              border-radius: 8px;
              box-shadow: var(--z-def-box-shadow);
              width: var(--z-dialog-width, max-content);
              min-width: 150px;
              background-color: var(--z-dialog-bgc,  oklch(1 0 0 / 1));
              margin-top: 10vh;
              color: var(--z-dialog-color, var(--z-text-color));
              overflow: auto;
              max-height: 70vh;
            }
            
            #dialog::backdrop {
              background-color: rgba(0, 0, 0, 0.5);
     
              /*backdrop-filter: blur(1px);*/
              /*background-color: transparent;*/
            }
            
            .header {
              font-size: 1.2em;
              font-weight: bold;
              margin-bottom: 1rem;
            }
            
            .content {
              margin-bottom: 1.5rem;
              line-height: 1.5;
            }
            
            .actions {
              display: flex;
              gap: 8px;
              justify-content: flex-end;
            }
            
            button {
              padding: 6px 12px;
              border-radius: 4px;
              cursor: pointer;
              transition: opacity 0.2s;
              border: none;
            }
            
            .confirm-btn {
              background-color: var(--z-dialog-confirm-bgc, var(--z-color-info));
              color: var(--z-dialog-confirm-color, #fff);
              border: none;
            }
            
            button:hover {
              opacity: 0.9;
            }
          </style>
          
          <slot name="trigger"></slot>
          
          <dialog id="dialog" popover="manual">
            <div class="header"></div>
            <div class="content" id="content"><slot name="content"></slot></div>
            <div class="actions">
              <button type="button" class="confirm-btn"></button>
              <button popovertarget="dialog" popovertargetaction="hide">取消</button>
            </div>
          </dialog>
        `;
        /**
         *
         * @type {HTMLTemplateElement | null}
         * @private
         */
        this._template = null;

        this._bindRet = null;

    }

    static get observedAttributes() {
        return ['dialog-title', 'confirm-text']; // 移除 dialog-content
    }

    connectedCallback() {
        this._bindRet = initRootEvents(this._shadowRoot)
        /**
         *
         * @type {HTMLTemplateElement}
         */
        let prerender = this.querySelector('template[name=prerender]');
        if (prerender) {
            this._shadowRoot.append(prerender.content.cloneNode(true));
        }

        this._template = this.querySelector('template[name=content]');
        // console.log('this._template', this._template)
        this._updateHeader();
        this._setupEventListeners();
    }

    disconnectedCallback() {
        if (this._bindRet && this._bindRet.destroy) {
            this._bindRet.destroy();
        }
    }

    attributeChangedCallback(name) {
        if (name === 'dialog-title' || name === 'confirm-text') {
            this._updateHeader();
        }
    }

    _updateHeader() {
        // 只更新标题和按钮文本
        this._shadowRoot.querySelector('.header').textContent =
            this.getAttribute('dialog-title') || '提示';

        this._shadowRoot.querySelector('.confirm-btn').textContent =
            this.getAttribute('confirm-text') || '确认';
    }

    _setupEventListeners() {
        // console.dir( this._shadowRoot.querySelector('[name="trigger"]'))
        let self = this;
        const trigger = this._shadowRoot.querySelector('[name="trigger"]');
        trigger.addEventListener('click', () => this._showDialog());

        const confirmBtn = this._shadowRoot.querySelector('.confirm-btn');
        confirmBtn.addEventListener('click', () => this._handleConfirm());

        document.addEventListener('keyup', function(e) {
            if (e.key === "Escape") { // escape key maps to keycode `27`
                // <DO YOUR WORK HERE>
                self.toggle(false);
            }
        });

        this.getDomById('dialog')
            .addEventListener('beforetoggle', (e) => {
                if (e.newState === "open") {
                    this._toggleOpenState(true);
                } else {
                    this._toggleOpenState(false);
                }
            });
    }

    toggle(show = true) {
        if (show && !this._internals.states.has('open')) {
            this._showDialog()
        }
        else {
            this._hideDialog()
        }
    }

    showModalApp(option = {}) {
        if (!option.data) {
            option.data = function () {
                return {}
            }
        }
        // console.log('sssssssssssssss showModal')
        this.dialogFrameWorkOption = option
        this.toggle();
        return  this.htmlapp
    }

    _ensureModalOpen(open) {
        if (!isSupportPopover()) {
            this._toggleOpenState(open)
        }
    }

    _buildApp() {
        if (this._template) {
            this.getDomById('content')
                .append(this._template.content.cloneNode(true));
        }
        console.log('_buildApp dialogFrameWorkOption', this.dialogFrameWorkOption)
        this.htmlapp = buildSimpleApp(this.dialogFrameWorkOption);
        this.htmlapp.mount(this._shadowRoot);
        globalThis._dialoghtmlapp = this.htmlapp;
    }

    _destoryApp() {
        this.getDomById('content').innerHTML = ''
        this.htmlapp = null
    }

    _toggleOpenState(open) {
        if (open) {
            this.classList.add('dialog-open');
            this._internals.states.add('dialog-open');
            this._buildApp()
        }
        else {
            this.classList.remove('dialog-open');
            this._internals.states.delete('open');
            this._destoryApp()
            this.dispatchEvent(new CustomEvent('hide', {
                bubbles: true,
                composed: true
            }));
        }
    }

    _showDialog() {
        this.getDomById('dialog').showPopover();
        this._ensureModalOpen(true);
    }

    _hideDialog() {
        this.getDomById('dialog').hidePopover();
        this._ensureModalOpen(false);
    }

    _handleConfirm() {
        this.dispatchEvent(new CustomEvent('confirm', {
            bubbles: true,
            composed: true
        }));
        this._hideDialog();
    }
}

customElements.define('z-dialog', DialogPopover);